package com.easyOrder.service.branch;

import com.easyOrder.core.utils.WebUtils;
import com.easyOrder.dao.BranchMapper;
import com.easyOrder.dao.UserBranchMapper;
import com.easyOrder.dao.UserMapper;
import com.easyOrder.dto.BranchDTO;
import com.easyOrder.model.*;
import com.easyOrder.service.enums.BranchState;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Created by liutao on 2017/7/20.
 */
@Service
public class BranchService {

    @Autowired
    private BranchMapper branchMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserBranchMapper userBranchMapper;

    /**
     * 通过id查询门店
     * @param branchId
     * @return
     */
    public Branch findById(Long branchId){
        Branch branch = branchMapper.selectByPrimaryKey(branchId);
        return branch;

    }

    /**
     * 查询用户门店
     * @return
     */
    public List<BranchDTO> findBranch(){
        List<BranchDTO> branchDTOS = Lists.newArrayList();
        List<Branch> branches;
        Boolean tenantManager = WebUtils.Session.get().getTenantManager();
        Long userId = WebUtils.Session.get().getUserId();
        if (tenantManager != null && tenantManager) {
            User user = userMapper.selectByPrimaryKey(userId);
            BranchExample example = new BranchExample();
            example.createCriteria().andTenantIdEqualTo(user.getTenantId()).andStatusIdEqualTo(BranchState.normal.getValue());
            branches = branchMapper.selectByExample(example);
        }else{
            UserBranchExample example = new UserBranchExample();
            example.createCriteria().andUserIdEqualTo(userId);
            List<UserBranch> userBranches = userBranchMapper.selectByExample(example);
            Set<Long> branchIds = userBranches.stream().map(userBranch -> userBranch.getBranchId()).collect(Collectors.toSet());
            if(CollectionUtils.isEmpty(branchIds)){
                return branchDTOS;
            }
            BranchExample branchExample = new BranchExample();
            branchExample.createCriteria().andIdIn(Lists.newArrayList(branchIds))
                    .andStatusIdEqualTo(BranchState.normal.getValue());
            branches = branchMapper.selectByExample(branchExample);
        }
        if(CollectionUtils.isEmpty(branches)){
            return branchDTOS;
        }
        branches.forEach(branch -> {
            BranchDTO branchDTO = new BranchDTO();
            branchDTO.setBranchId(branch.getId());
            branchDTO.setBranchName(branch.getName());
            branchDTOS.add(branchDTO);
        });
        return branchDTOS;
    }
}
